package com.ruoyi.base.permission;

import com.ruoyi.base.enums.ExceptionEnum;
import com.ruoyi.base.exception.SysException;
import com.ruoyi.platform.system.menu.enums.MenuEnum;
import com.ruoyi.platform.system.role.dao.menu.RoleMenuRdbDAO;
import com.ruoyi.platform.system.role.enums.RoleIdEnum;
import com.ruoyi.platform.system.user.dao.role.UserRoleDAO;
import com.ruoyi.platform.system.user.pojo.role.UserRoleDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 权限判断
 *
 * @author ruoyi
 */
@Component
public class PermissionManager {
    @Autowired
    private UserRoleDAO userRoleRdbDAO;
    @Autowired
    private RoleMenuRdbDAO roleMenuRdbDAO;

    /**
     * 检查角色权限
     */
    public void checkRolePermission(List<Long> roleIdList, MenuEnum menu) {
        if (menu == null || CollectionUtils.isEmpty(roleIdList)) {
            throw new SysException(ExceptionEnum.NO_PERMISSION);
        }

        if (roleMenuRdbDAO.selectCountByRole(roleIdList, menu.getCode()) > 0) {
            return;
        }

        throw new SysException(ExceptionEnum.NO_PERMISSION);
    }

    /**
     * 检查用户权限
     */
    public void checkUserPermission(long userId, MenuEnum[] menus) {
        if (Arrays.asList(menus).isEmpty()) {
            return;
        }

        List<UserRoleDO> userRoleList = userRoleRdbDAO.selectByUserRole(new UserRoleDO(userId));
        if (CollectionUtils.isEmpty(userRoleList)) {
            throw new SysException(ExceptionEnum.NO_PERMISSION);
        }

        List<Long> roleIdList = userRoleList.stream().map(UserRoleDO::getRoleId).collect(Collectors.toList());
        Optional<Long> opt = roleIdList.stream().filter(x -> Objects.equals(x, RoleIdEnum.SUPER_ADMIN.getRoleId())).findAny();
        if (opt.isPresent()) {
            return;
        }

        for (MenuEnum menu : menus) {
            checkRolePermission(roleIdList, menu);
        }
    }
}
